//
//  ButtonGroup.m
//  TaduFramework
//
//  Created by Xu Deheng on 12-6-18.
//  Copyright (c) 2012年 Nicholas.Xu. All rights reserved.
//

#import "ButtonsGroup.h"
#import "FunctionSet.h"

#if TARGET_OS_IPHONE

#pragma definition of ButtonsGroup

@interface ButtonsGroup ()

- (void)_listenButtonClickState:(id)sender;

@end

#pragma mark - ButtonsGroup implementation
@implementation ButtonsGroup
@synthesize buttons = _buttons;
@synthesize multiSelection = _multiSelection;
@synthesize lastSelectedIndex = _lastSelectedIndex;
@synthesize selectedIndex = _selectedIndex;
@dynamic pressedButton, lastButton;
@synthesize groupPanel = _groupPanel;

- (id)init
{
    self = [super init];
    if (self) {
        _buttons = [[NSMutableArray alloc] initWithCapacity:8];
        _multiSelection = NO;
    }
    return self;
}

#if !ARC_ENABLED
- (void)dealloc
{
    [_buttons release];
    [super dealloc];
}
#endif

- (BOOL)addGroupButton:(GroupButton *)object
{
    if (!object || ![object isKindOfClass:[GroupButton class]]) {
#if kButtons_GroupLogging
        NSLog(@"%s object未初始化或者不为 UIButton 对象!", __func__);
#endif
        return NO;
    }
    if ([_buttons containsObject:object]) {
#if kButtons_GroupLogging
        NSLog(@"%s object 重复!", __func__);
#endif
        return NO;
    }
    
    [_buttons addObject:object];
    if (_groupPanel) {
        [_groupPanel addSubview:object];
        object.zPositionOfView = [_groupPanel.subviews indexOfObject:object];
    }
    
    [object addTarget:self action:@selector(_listenButtonClickState:) forControlEvents:UIControlEventTouchUpInside];
    
    return YES;
}

- (BOOL)removeGroupButton:(UIButton *)object
{
    if (!object || ![object isKindOfClass:[UIButton class]]) {
#if kButtons_GroupLogging
        NSLog(@"%s object未初始化或者不为 UIButton 对象!", __func__);
#endif
        return NO;
    }
    if (![_buttons containsObject:object]) {
#if kButtons_GroupLogging
        NSLog(@"%s object 不在组内!", __func__);
#endif
    }    
    
    [object removeTarget:self action:@selector(_listenButtonClickState:) forControlEvents:UIControlEventTouchUpInside];
    
    [_buttons removeObject:object];
    return YES;
}

- (BOOL)removeAllButtons
{
    NSMutableArray *_tmp = XRetain(self.buttons);
    for (GroupButton *btn in _tmp) {
        [btn removeTarget:self action:@selector(_listenButtonClickState:) forControlEvents:UIControlEventTouchUpInside];
    }
    XRelease(_tmp);
    
    [_buttons removeAllObjects];
    return YES;
}

- (void)reorderZPosition
{
    UIView *__superview = nil;
    for (GroupButton *gb in self.buttons) {
        if (nil == __superview) {
            __superview = gb.superview;
            continue;
        }else {
            NSAssert([gb.superview isEqual:__superview], @"Button superview are not the same!");
        }
    }
}

- (NSUInteger)indexOfButton:(UIButton *)button
{
    return [self.buttons indexOfObject:button];
}

#pragma mark - hidden methods
//按钮被有效选择
- (void)_listenButtonClickState:(id)sender
{
#if kButtons_GroupLogging
    NSLog(@"%s", __func__);
#endif
    GroupButton *btn = sender;
    if (![btn isKindOfClass:[UIButton class]]) {
        return;
    }
    
    if ([_buttons containsObject:sender]) {
        if (_lastSelectedIndex != _selectedIndex) {
            _lastSelectedIndex = _selectedIndex;
        }
        _selectedIndex = [self.buttons indexOfObject:sender];
        
        btn.zPositionOfView = [btn.superview.subviews indexOfObject:btn];
        
        NSLog(@"selected :%u, lastSelected :%u", _selectedIndex, _lastSelectedIndex);
        if (_multiSelection) {
            if (btn.isPressed) {
                [btn switchToUnpressedView];
            }else {
                [btn switchToPressedView];
            }
        }
        else {
            for (GroupButton *gb in _buttons) {
                if ([gb isKindOfClass:[GroupButton class]] && ![gb isEqual:btn]) {
                    [gb switchToUnpressedView];
                }
            }
            if ([btn isKindOfClass:[GroupButton class]]) {
                if ([btn respondsToSelector:@selector(switchToPressedView)]) {
                    [btn switchToPressedView];
                }
                [btn.superview bringSubviewToFront:btn];
            }
        }
    }
}

- (void)pressButtonAtIndex:(NSUInteger)index
{
    if (self.buttons.count == 0) {
        return;
    }
    if (index >= self.buttons.count) {
        return;
    }
    [self performSelector:@selector(_listenButtonClickState:) withObject:[self.buttons objectAtIndex:index]];
}

- (void)pressButton:(UIButton *)pressedButton
{
    NSUInteger _index = [_buttons indexOfObject:pressedButton];
    if (_index == NSNotFound) {
        return;
    }
    [self _listenButtonClickState:pressedButton];
}

- (UIButton *)pressedButton
{
    if (_selectedIndex != NSNotFound && _selectedIndex < self.buttons.count) {
        return [self.buttons objectAtIndex:_selectedIndex];
    }
    return nil;
}

- (UIButton *)lastButton
{
    if (_lastSelectedIndex != NSNotFound && _lastSelectedIndex < self.buttons.count) {
        return [self.buttons objectAtIndex:_lastSelectedIndex];
    }
    return nil;
}

- (UIButton *)buttonAtIndex:(NSUInteger)index
{
    if (index != NSNotFound && index < self.buttons.count) {
        return [self.buttons objectAtIndex:index];
    }
    return nil;
}

@end


#pragma mark - GroupButton implementation
@implementation GroupButton

@synthesize pressedImage = _pressedImage;
@synthesize unpressedImage = _unpressedImage;
@synthesize pressed = _pressed;
@synthesize pressedTitleColor = _pressedTitleColor;
@synthesize unpressedTitleColor = _unpressedTitleColor;
@synthesize zPositionOfView = _zPositionOfView;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self loadDefaultData];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadDefaultData];
    }
    return self;
}

#if !ARC_ENABLED
- (void)dealloc
{
    [_pressedImage release];
    [_unpressedImage release];
    [_pressedTitleColor release];
    [_unpressedTitleColor release];
    [super dealloc];
}
#endif

- (void)loadDefaultData
{
    if (!_pressedTitleColor) {
        _pressedTitleColor = XRetain([UIColor blackColor]);
    }
    if (!_unpressedTitleColor) {
        _unpressedTitleColor = XRetain([UIColor whiteColor]);
    }
    _zPositionOfView = 0;
}

- (void)switchToPressedView
{
#if kGroupButtonLogging
    NSLog(@"%s", __func__);
#endif
    self.pressed = YES;
    //ToDo:add code for presentation pressed
    if (_pressedTitleColor) {
        [self setTitleColor:_pressedTitleColor forState:UIControlStateNormal];
    }
    if (_pressedImage) {
        [self setBackgroundImage:_pressedImage forState:UIControlStateNormal];
    }
}

- (void)switchToUnpressedView
{
#if kGroupButtonLogging
    NSLog(@"%s", __func__);
#endif
    self.pressed = NO;
    //ToDo:add code for presentation pressed
    if (_unpressedTitleColor) {
        [self setTitleColor:_unpressedTitleColor forState:UIControlStateNormal];
    }
    if (_unpressedImage) {
        [self setBackgroundImage:_unpressedImage forState:UIControlStateNormal];    
    }
}

- (void)updateZPositionOfView
{
    if (self.superview) {
        self.zPositionOfView = [self.superview.subviews indexOfObject:self];
    }
}

@end

#endif





